package com.zenithsun.news.newscolumns.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.syzg.base.aduit.model.Audit;
import com.syzg.common.config.SysProperties;
import com.syzg.common.controller.BaseController;
import com.syzg.common.model.WebInfo;
import com.syzg.common.util.SearchMap;
import com.syzg.common.util.MethodUtil;
import com.syzg.common.util.SystemUtil;
import com.syzg.common.model.WebObj;
import com.syzg.common.util.PKCreator;
import com.syzg.common.exception.BaseException;
import com.syzg.core.page.PageResult;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.zenithsun.news.newscolumns.model.NewsColumns;
import com.zenithsun.news.newscolumns.service.NewsColumnsService;
import com.zenithsun.news.newsinfo.model.Newsinfo;
import com.zenithsun.news.newsinfo.service.NewsinfoService;
import com.zenithsun.common.bean.OutMessage;
import com.zenithsun.common.bean.OutMessageState;

@Controller
@RequestMapping("/path/newscolumns")
public class NewsColumnsController extends BaseController{
	
	static Logger log = LoggerFactory.getLogger(NewsColumnsController.class);
	
	@Resource
	private NewsColumnsService newscolumnsService;
	@Resource
	private NewsinfoService newsInfoService;
	/**
	 * 设置查询条件
	 * @param webObj
	 * @param searchMap
	 */
	private void setSearchCondition(WebObj webObj,SearchMap searchMap){
		//1：从webObj中获取查询的参数webObj.getSearchValue().get("参数名称");
		//2：判断参数是否为空或空值
		//3：设置查询条件searchMap.eq("a.参数名称", 参数值);
		String id=webObj.getSearchValue().get("id");
		if(StringUtils.isNotBlank(id)){
			searchMap.eq("a.id", id);
		}
		String name=webObj.getSearchValue().get("name");
		if(StringUtils.isNotBlank(name)){
			searchMap.like("a.name", name);
		}
		String parentId=webObj.getSearchValue().get("parentId");
		if(StringUtils.isNotBlank(parentId)){
			searchMap.eq("a.parentId", parentId);
		}
		//增加排序条件
		//按序号进行升序
		searchMap.addOrder("a.orderNo", SearchMap.ORDER_ASC);
	}
	
	@RequestMapping("/listnewscolumns")
	public ModelAndView listnewscolumns(WebObj webObj)throws Exception{
		ModelAndView mv = new ModelAndView("/zenithsun/news/newscolumns/listnewscolumns.jsp");
		SearchMap searchMap = SearchMap.forClass(NewsColumns.class);
		setSearchCondition(webObj,searchMap);
		PageResult pageResult = newscolumnsService.findObjectsForPage(webObj.getPageNo(), SysProperties.PAGESIZE, searchMap);
        webObj.setPageResult(pageResult);
        mv.addObject("webObj",webObj);
        return mv;
	}
	
	@RequestMapping("/initnewscolumns")
	public ModelAndView initnewscolumns() throws Exception {
		ModelAndView mv = new ModelAndView("/zenithsun/news/newscolumns/addnewscolumns.jsp");
		try {
			mv.addObject("newscolumns", new NewsColumns());
			/*LoginObject loginObj = SystemUtil.getLoginObject();
			this.newscolumns.setCreatePersonId(new String(loginObj.getPersonId()));
			this.newscolumns.setCreator(loginObj.getPersonName());
			this.newscolumns.setCreateTime(new Date());*/
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/addnewscolumns")
	public @ResponseBody String addnewscolumns(Audit audit,NewsColumns newscolumns,HttpServletRequest request) throws Exception {
		WebObj webObj = new WebObj();
		try {
			
			/*LoginObject loginObj = SystemUtil.getLoginObject();
			this.newscolumns.setCreatePersonId(new String(loginObj.getPersonId()));
			this.newscolumns.setCreator(loginObj.getPersonName());
			this.newscolumns.setCreateTime(new Date());*/
			newscolumns.setId(PKCreator.getPk());
			newscolumns.setCreateTime(new Date());
			if(StringUtils.isBlank(newscolumns.getParentId())){
				newscolumns.setParentId("0");
			}
			newscolumnsService.create(newscolumns);
//			audit.setId(PKCreator.getPk());
//			audit.setOperateTime(new Date());
//			audit.setOperateDescribe("新增名称为["+newscolumns.getName()+"]的栏目");
			String id = SystemUtil.getLoginPersonId();
//			audit.setUserId(id);
//			newscolumnsService.create(audit);
			setControllerStatus(webObj,WebInfo.STATUS_SUCCESS);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			setControllerStatus(webObj,WebInfo.STATUS_FAILURE);
			webObj.getWebInfo().getErrorList().add("操作失败");
		}
		return new JSONObject(webObj).toString();
	}
	
	@RequestMapping("/viewnewscolumns")
	public ModelAndView viewnewscolumns(NewsColumns newscolumns,ModelAndView mv) throws Exception {
		mv.setViewName("/zenithsun/news/newscolumns/viewnewscolumns.jsp");
		try {
			String id = newscolumns.getId();
			NewsColumns newscolumnsVO = newscolumnsService.findObjectById(id);
			mv.addObject("newscolumns",newscolumnsVO);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/editnewscolumns")
	public ModelAndView editnewscolumns(String id) throws Exception {
		ModelAndView mv = new ModelAndView("/zenithsun/news/newscolumns/editnewscolumns.jsp");
		try {
			NewsColumns newscolumns = newscolumnsService.findObjectById(id);
			mv.addObject("newscolumns", newscolumns);
			WebObj webObj = new WebObj();
			mv.addObject("webObj",webObj);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return mv;
	}
	
	@RequestMapping("/modnewscolumns")
	public @ResponseBody String modnewscolumns(String id,NewsColumns newscolumnsVO) throws Exception {
		WebObj webObj = new WebObj();
		try {
			NewsColumns newscolumns = newscolumnsService.findObjectById(id);
			if(StringUtils.isBlank(newscolumnsVO.getParentId())){
				newscolumnsVO.setParentId("0");
			}
			newscolumns = (NewsColumns) MethodUtil.copyProperties(newscolumns, newscolumnsVO);
			newscolumnsService.update(newscolumns);
			setControllerStatus(webObj,WebInfo.STATUS_SUCCESS);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			setControllerStatus(webObj,WebInfo.STATUS_FAILURE);
			webObj.getWebInfo().getErrorList().add("操作失败");
		}
		return new JSONObject(webObj).toString();
	}

	@RequestMapping("/delnewscolumns")
	public ModelAndView delnewscolumns(String id,WebObj webObj) throws Exception {
		String[] ids = webObj.getSelectedRow();
		try {
			if(ids == null) { //删除单个
				if(id == null) {
					ids = new String[0];
				} else {
					ids = new String[]{String.valueOf(id)};
				}
			}
//			String[] idsStr = new String[ids.length];
//			int i = 0;
//			for(String idVO: ids) {
//				idsStr[i++] = new String(idVO);
//			}
			newscolumnsService.delete(ids);
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
		return listnewscolumns(webObj);
	}
	
	/**
	 * 加载树形栏目页面
	 * @author wanglei@enersun.com.cn
	 * @param mv
	 * @return json数据
	 * @throws Exception
	 */
	@RequestMapping("/treenewscolumns")
	public ModelAndView treenewscolumns(ModelAndView mv) throws Exception {
		mv.setViewName("/zenithsun/news/newscolumns/treenewscolumns.jsp");
		return mv;
	}
	
	/**
	 * 获取树形栏目列表
	 * @author wanglei@enersun.com.cn
	 * @param mv
	 * @return json数据
	 * @throws Exception
	 */
	@RequestMapping(value="/loadtreenewscolumns",produces="application/json;charset=UTF-8")
	public @ResponseBody String loadtreenewscolumns() throws Exception {
		OutMessage outMessage=new OutMessage();
		try {
			outMessage.setState(OutMessageState.Success);
			outMessage.setContent(newscolumnsService.getTreeNewsColumns());
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			outMessage.setState(OutMessageState.Error);
			outMessage.setContent("操作失败");
		}
		return JSON.toJSONString(outMessage, SerializerFeature.WriteNullStringAsEmpty);
	}
	/**
	 * 批量删除 
	 * @return json
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteByIds",produces="application/json;charset=UTF-8")
	@ResponseBody
	public String deleteByIds(String[] ids) throws Exception{
		OutMessage outMessage=new OutMessage();
		String msg = "";
		try {
			NewsColumns column = new NewsColumns();
			Newsinfo info = new Newsinfo();
			for (int i = 0; i < ids.length; i++) {
				//获取NewsColumns
				column = newscolumnsService.findObjectById(ids[i]);
				info.setNewsColumns(column);
				//判断是否有新闻
				if(newsInfoService.queryNewsinfo(1, 100, info).getTotalCount() > 0 ){
					msg += "× ["+column.getName() + "]下有关联新闻,不能删除;";
				}else{
					newscolumnsService.delete(ids[i]);
					msg += "√ ["+column.getName() + "]已删除;";
				}
			}
			outMessage.setState(OutMessageState.Success);
			outMessage.setContent(msg);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			outMessage.setState(OutMessageState.Fail);
			outMessage.setContent("操作失败");
		}
		return JSON.toJSONString(outMessage);
	}
	
	/**
	 * 获取第一级栏目列表，并提供给终端使用
	 * @author wanglei@enersun.com.cn
	 * @return json数据
	 * @throws Exception
	 */
	@RequestMapping(value="/jsonnewscolumns",produces="application/json;charset=UTF-8")
	public @ResponseBody String jsontreenewscolumns() throws Exception {
		OutMessage outMessage=new OutMessage();
		try {
			outMessage.setState(OutMessageState.Success);
			outMessage.setContent(newscolumnsService.getFirstFloorNewsColumns());
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
			outMessage.setState(OutMessageState.Error);
			outMessage.setContent("操作失败");
		}
		return JSON.toJSONString(outMessage, SerializerFeature.WriteNullStringAsEmpty);
	}
}